<template>
  <div class="admin-home-container">
    <div class="page-header">
      <h2>数据统计</h2>
      <p>系统数据分析与可视化</p>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-title">非遗数量</div>
          <div class="stat-value">{{ statsData.heritageCount }}</div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-title">用户数量</div>
          <div class="stat-value">{{ statsData.userCount }}</div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-title">活动数量</div>
          <div class="stat-value">{{ statsData.activityCount }}</div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-title">活动累计报名人数</div>
          <div class="stat-value">{{ statsData.totalRegistration }}</div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 近一周活动报名统计 -->
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>近一周活动报名统计</span>
            <el-select v-model="timeRange" size="small" class="time-select" @change="updateCharts">
              <el-option label="近7天" value="7d"></el-option>
              <el-option label="近30天" value="30d"></el-option>
              <el-option label="近90天" value="90d"></el-option>
            </el-select>
          </div>
        </template>
        <div class="chart-wrapper">
          <div id="activityRegistrationChart" class="chart"></div>
        </div>
      </el-card>

      <!-- 分类非遗数量统计 -->
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>分类非遗数量统计</span>
            <el-button type="text" size="small" class="refresh-btn" @click="refreshCharts">
              <i class="el-icon-refresh"></i>
              刷新
            </el-button>
          </div>
        </template>
        <div class="chart-wrapper">
          <div id="heritageCategoryChart" class="chart"></div>
        </div>
      </el-card>
    </div>

    <!-- 更多统计信息 -->
    <div class="more-stats-container">



    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import {getDashboardStats, getHeritageCategories, getActivityRegistrations} from '@/api/dashboard.js'
import {ElMessage} from "element-plus";

// 响应式数据
const statsData = ref({
  heritageCount: 0,
  userCount: 0,
  activityCount: 0,
  totalRegistration: 0
})

const timeRange = ref('7d')

// 图表实例
let activityRegistrationChart = null
let heritageCategoryChart = null




// 获取仪表盘统计数据
const fetchDashboardStats = async () => {
  try {
    // 调用后端API获取真实数据
    const response = await getDashboardStats()
    if (response.success === true || response.errorCode === 20000){
      if ( response.data){
        statsData.value={
          heritageCount: response.data.heritageCount,
          userCount: response.data.userCount,
          activityCount: response.data.activityCount,
          totalRegistration: response.data.totalRegistration
        }
      }
    } else {
      ElMessage.error(response.message || '获取仪表盘信息失败')
    }
  } catch (error) {
    console.error('获取仪表盘统计数据失败:', error)
    // 使用默认数据作为降级方案
    statsData.value = {
      heritageCount: 0,
      userCount: 0,
      activityCount: 0,
      totalRegistration: 0
    }
  }
}

// 获取活动报名数据
const fetchActivityData = async () => {
  try {
    // 调用后端API获取真实数据
    const response = await getActivityRegistrations({ range: timeRange.value })
    
    if (response.success && response.errorCode === 20000 && response.data) {
      console.log('后端返回的活动报名数据:', response.data)
      return response.data
    } else {
      throw new Error(response.message || '获取活动报名数据失败')
    }
  } catch (error) {
    console.error('获取活动报名数据失败:', error)
    ElMessage.error('获取活动报名数据失败')
    // 返回默认模拟数据作为降级方案
    return {
      dates: ['2025-08-06', '2025-08-07', '2025-08-08', '2025-08-09', '2025-08-10', '2025-08-11', '2025-08-12'],
      counts: [1, 0, 2, 1, 3, 4, 4]
    }
  }
}

// 获取非遗分类数据
const fetchCategoryData = async () => {
  try {
    // 调用后端API获取真实数据
    const response = await getHeritageCategories()
    
    if (response.success && response.errorCode === 20000 && response.data) {
      console.log('后端返回的原始数据:', response.data)
      
      // 直接使用后端返回的数据，转换为饼图所需的格式
      const result = response.data.map(item => ({
        name: item.categoryName || `分类${item.categoryId}`,
        value: item.count || 0
      }))
      
      console.log('转换后的饼图数据:', result)
      
      // 如果没有数据，返回默认的模拟数据以便展示饼图效果
      if (result.length === 0) {
        return [
          { name: '民间文学', value: 8 },
          { name: '传统舞蹈', value: 6 },
          { name: '节日仪式', value: 4 },
          { name: '民间音乐', value: 5 },
          { name: '传统技艺', value: 3 },
          { name: '运动项目', value: 1 }
        ]
      }
      
      return result
    } else {
      throw new Error(response.message || '获取分类数据失败')
    }
  } catch (error) {
    console.error('获取非遗分类数据失败:', error)
    ElMessage.error('获取分类数据失败')
    // 返回默认模拟数据作为降级方案
    return [
      { name: '民间文学', value: 8 },
      { name: '传统舞蹈', value: 6 },
      { name: '节日仪式', value: 4 },
      { name: '民间音乐', value: 5 },
      { name: '传统技艺', value: 3 },
      { name: '运动项目', value: 1 }
    ]
  }
}



// 初始化活动报名统计图表
const initActivityRegistrationChart = async () => {
  const chartDom = document.getElementById('activityRegistrationChart')
  if (!chartDom) return
  
  activityRegistrationChart = echarts.init(chartDom)
  const data = await fetchActivityData()
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        const date = params[0].name
        const count = params[0].value
        return `${date}<br/>报名人数: ${count} 人`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: data.dates,
        axisLabel: {
          rotate: 45,
          interval: 0,
          formatter: function(value) {
            return value.slice(5) // 只显示月-日
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '人数',
        min: 0,
        max: function(value) {
          return Math.max(value.max, 5)
        },
        interval: function(value) {
          return Math.ceil((value.max - value.min) / 5)
        }
      }
    ],
    series: [
      {
        name: '报名人数',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#1a5276'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(26, 82, 118, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(26, 82, 118, 0.05)'
            }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        data: data.counts,
        markPoint: {
          symbol: 'circle',
          symbolSize: 8,
          data: [
            {
              type: 'max',
              name: '最大值'
            },
            {
              type: 'min',
              name: '最小值'
            }
          ],
          itemStyle: {
            color: '#f44336'
          }
        }
      }
    ]
  }
  
  activityRegistrationChart.setOption(option)
}

// 初始化分类非遗数量统计图表
const initHeritageCategoryChart = async () => {
  const chartDom = document.getElementById('heritageCategoryChart')
  if (!chartDom) {
    console.error('找不到图表容器元素')
    return
  }
  
  heritageCategoryChart = echarts.init(chartDom)
  const data = await fetchCategoryData()
  
  console.log('初始化饼图时使用的数据:', data)
  
  // 设置默认颜色
  const defaultColors = ['#1a5276', '#2980b9', '#3498db', '#85c1e9', '#f4d03f', '#d68910']
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        // 自定义tooltip格式，显示名称、数量和百分比
        return `${params.seriesName}<br/>${params.name}: ${params.value} (${params.percent}%)`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      textStyle: {
        fontSize: 12
      },
      // 确保图例项数量与数据一致
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '非遗分类',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['65%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: function(params) {
            // 只在数值大于0时显示标签
            return params.value > 0 ? `${params.name}\n${params.percent}%` : ''
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
            formatter: function(params) {
              return `${params.name}\n${params.value}项 (${params.percent}%)`
            }
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: true,
          lineStyle: {
            color: '#666'
          }
        },
        data: data,
        color: defaultColors.slice(0, data.length) // 根据数据数量调整颜色数量
      }
    ]
  }
  
  heritageCategoryChart.setOption(option)
}


// 初始化所有图表
const initCharts = async () => {
  await Promise.all([
    initActivityRegistrationChart(),
    initHeritageCategoryChart()
  ])
}

// 更新图表（时间范围变化时）
const updateCharts = async () => {
  await initActivityRegistrationChart()
}

// 刷新所有图表
const refreshCharts = async () => {
  await initCharts()
}

// 监听窗口大小变化
const handleResize = () => {
  if (activityRegistrationChart) activityRegistrationChart.resize()
  if (heritageCategoryChart) heritageCategoryChart.resize()
}

// 组件挂载时初始化
onMounted(async () => {
  await fetchDashboardStats()
  await nextTick()

  await initCharts()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (activityRegistrationChart) activityRegistrationChart.dispose()
  if (heritageCategoryChart) heritageCategoryChart.dispose()
})
</script>

<style scoped>
.admin-home-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 25px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  height: 120px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  margin-right: 20px;
}

.heritage-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.user-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.activity-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.participant-icon {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #2c3e50;
  line-height: 1.2;
}

/* 图表容器样式 */
.charts-container,
.more-stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.chart-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
}

.chart-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.chart-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.time-select {
  width: 100px;
}

.refresh-btn {
  color: #3498db;
}

.chart-wrapper {
  padding: 15px;
  height: 350px;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-home-container {
    padding: 15px;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .charts-container,
  .more-stats-container {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .chart-wrapper {
    height: 300px;
  }
  
  .stat-card {
    padding: 15px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 24px;
  }
}

@media (max-width: 480px) {
  .page-header h2 {
    font-size: 24px;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .chart-wrapper {
    height: 250px;
  }
}
</style>